<template>
  <div class="main-content">
    <div style="margin: 30px 0; text-align: center">
      <el-input size="large" clearable @clear="reset" style="width: 500px; margin-right: 5px" v-model="data.title" placeholder="请输入帖子标题查询"></el-input>
      <el-button size="large" type="primary" @click="load">查询</el-button>
      <el-button size="large" type="success" @click="initAdd" style="margin-left: 10px">发布学习经验</el-button>
    </div>
    <div>
      <el-row :gutter="20">
        <el-col :span="4.8" v-for="item in data.articleData" :key="item.id" style="margin-bottom: 20px">
          <div class="card" @click="navTo('/front/articleDetail?id=' + item.id)">
            <img :src="item.img" alt="" class="card-image">
            <div class="card-content">
              <div class="overflowShow card-title">{{ item.title }}</div>
              <div style="display: flex; align-items: center; margin-top: 10px;">
                <img :src="item.userImg" alt="" class="user-avatar">
                <div class="user-name" style="flex: 1; margin-left: 10px;">{{ item.userName }}</div>
                <div class="post-time" style="text-align: right;">{{ item.time }}</div>
              </div>
            </div>
          </div>
        </el-col>
      </el-row>
      <!-- 使用 el-empty 组件显示暂无数据 -->
      <el-empty v-if="data.articleData.length === 0 && !data.loading" description="暂无数据" />
    </div>
    <div v-if="data.total" style="margin: 20px 0; text-align: center;">
      <el-pagination @current-change="load" background layout="prev, pager, next" :page-size="data.pageSize" v-model:current-page="data.pageNum" :total="data.total" />
    </div>

    <!-- 发布学习经验弹窗 -->
    <el-dialog title="发布学习经验" v-model="data.formVisible" width="60%" destroy-on-close>
      <el-form ref="form" :model="data.form" label-width="70px" style="padding: 20px">
        <el-form-item prop="img" label="帖子封面">
          <el-upload
              :action="baseUrl + '/files/upload'"
              :on-success="handleFileUpload"
              list-type="picture"
          >
            <el-button type="primary">上传封面</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item prop="title" label="帖子标题">
          <el-input v-model="data.form.title" placeholder="请输入帖子标题"></el-input>
        </el-form-item>
        <el-form-item prop="content" label="帖子内容">
          <div style="border: 1px solid #ccc; width: 100%">
            <Toolbar
                style="border-bottom: 1px solid #ccc"
                :editor="editorRef"
                :mode="mode"
            />
            <Editor
                style="height: 500px; overflow-y: hidden;"
                v-model="data.form.content"
                :mode="mode"
                :defaultConfig="editorConfig"
                @onCreated="handleCreated"
            />
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="data.formVisible = false">取 消</el-button>
          <el-button type="primary" @click="save">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { reactive, shallowRef } from "vue";
import request from "@/utils/request.js";
import { ElMessage } from "element-plus";
import '@wangeditor/editor/dist/css/style.css'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import '@/assets/css/editor-content-view.css'
const baseUrl = import.meta.env.VITE_BASE_URL

const data = reactive({
  title: null,
  pageNum: 1,
  pageSize: 20, // Adjusted to fit 5 cards per row
  total: 0,
  articleData: [],
  formVisible: false,
  form: {},
  loading: false, // 添加加载状态标志
})

/* wangEditor5 初始化开始 */
const editorRef = shallowRef()  // 编辑器实例，必须用 shallowRef
const mode = 'default'
const editorConfig = { MENU_CONF: {} }
// 图片上传配置
editorConfig.MENU_CONF['uploadImage'] = {
  headers: {
    token: JSON.parse(localStorage.getItem('user') || '{}').token,
  },
  server: baseUrl + '/files/wang/upload',  // 服务端图片上传接口
  fieldName: 'file'  // 服务端图片上传接口参数
}
// 组件销毁时，也及时销毁编辑器，否则可能会造成内存泄漏
const handleCreated = (editor) => {
  editorRef.value = editor
}
/* wangEditor5 初始化结束 */

const load = () => {
  data.loading = true;
  request.get('/article/selectPage', {
    params: {
      pageNum: data.pageNum,
      pageSize: data.pageSize,
      title: data.title
    }
  }).then(res => {
    if (res.code === '200') {
      data.articleData = res.data.list;
      data.total = res.data.total;
    } else {
      ElMessage.error(res.msg);
    }
  }).finally(() => {
    data.loading = false;
  });
};

const reset = () => {
  data.title = null;
  load();
};

const navTo = (url) => {
  location.href = url;
};

const initAdd = () => {
  data.form = {};
  data.formVisible = true;
};

const save = () => {
  const url = data.form.id ? '/article/update' : '/article/add';
  request.post(url, data.form).then(res => {
    if (res.code === '200') {
      ElMessage.success('操作成功');
      data.formVisible = false;
      load();
    } else {
      ElMessage.error(res.msg);
    }
  }).catch(err => {
    ElMessage.error('操作失败，请检查输入');
    console.error(err);
  });
};

const handleFileUpload = (res) => {
  data.form.img = res.data;
};

load();
</script>

<style scoped>
.main-content {
  padding: 20px;
}

.card {
  position: relative;
  border-radius: 8px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  transition: transform 0.2s ease-in-out, box-shadow 0.2s ease-in-out;
  cursor: pointer;
  overflow: hidden;
  background-color: #fff;
  height: 100%;
}

.card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.2);
}

.card-image {
  width: 100%;
  height: 150px;
  object-fit: cover;
}

.card-content {
  padding: 15px;
}

.card-title {
  font-size: 16px;
  font-weight: bold;
  color: #333333;
}

.user-avatar {
  width: 25px;
  height: 25px;
  border-radius: 50%;
  object-fit: cover;
}

.user-name {
  font-size: 14px;
  color: #666666;
}

.post-time {
  font-size: 14px;
  color: #999999;
}

.overflowShow {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.el-col {
  width: calc(20% - 20px); /* Ensure each column takes up 20% minus gutter */
  box-sizing: border-box;
}
</style>



